﻿using IOP.OpenType.Tables;
using IOP.OpenType;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace IOP.Codec.OpenType
{
    /// <summary>
    /// 横向度量加载器
    /// </summary>
    public class HmtxTableLoader
    {
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="entry"></param>
        /// <param name="numGlyphs"></param>
        /// <param name="numberOfHMetrics"></param>
        /// <returns></returns>
        public async Task<HmtxTable> Load(FileStream stream, TableEntry entry, ushort numGlyphs, ushort numberOfHMetrics)
        {
            uint offset = entry.Offset;
            stream.Seek(offset, SeekOrigin.Begin);
            var pipe = new Pipe();
            var w = WriteToPipe(stream, pipe.Writer, entry);
            var r = ReadFromPipe(pipe.Reader, entry, numGlyphs, numberOfHMetrics);
            await Task.WhenAll(w, r);
            HmtxTable hmtxTable = r.Result;
            return hmtxTable;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="writer"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private async Task WriteToPipe(Stream stream, PipeWriter writer, TableEntry entry)
        {
            try
            {
                long already = 0;
                while (true)
                {
                    Memory<byte> memory = writer.GetMemory(2048);
                    int bytesRead = await stream.ReadAsync(memory);
                    writer.Advance(bytesRead);
                    already += bytesRead;
                    if (bytesRead == 0 || already >= entry.Length) break;
                    FlushResult result = await writer.FlushAsync();
                    if (result.IsCompleted) break;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                writer.Complete();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="entry"></param>
        /// <param name="numGlyphs"></param>
        /// <param name="numberOfHMetrics"></param>
        /// <returns></returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private async Task<HmtxTable> ReadFromPipe(PipeReader reader, TableEntry entry, ushort numGlyphs, ushort numberOfHMetrics)
        {
            try
            {
                HmtxTable table = new HmtxTable();
                table.Entry = entry;
                table.HMetrics = new LongHorMetric[numberOfHMetrics];
                table.LeftSideBearings = new short[numGlyphs - numberOfHMetrics];
                long finalBytes = entry.Length;
                long byteIndex = 0;
                long consumed = 0;
                int index = 0;
                while (true)
                {
                    ReadResult result = await reader.ReadAsync();
                    ReadOnlySequence<byte> buffer = result.Buffer;
                    ReadMetric(ref buffer, ref byteIndex, ref index, table.HMetrics);
                    consumed += byteIndex;
                    reader.AdvanceTo(buffer.GetPosition(byteIndex));
                    if (consumed >= finalBytes || index >= numberOfHMetrics) break;
                    byteIndex = 0;
                }
                byteIndex = 0;
                index = 0;
                while (true)
                {
                    ReadResult result = await reader.ReadAsync();
                    ReadOnlySequence<byte> buffer = result.Buffer;
                    ReadLsb(ref buffer, ref byteIndex, ref index, table.LeftSideBearings);
                    consumed += byteIndex;
                    reader.AdvanceTo(buffer.GetPosition(byteIndex));
                    if (consumed >= finalBytes || index >= numGlyphs - numberOfHMetrics) break;
                    byteIndex = 0;
                }
                return table;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Complete();
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void ReadMetric(ref ReadOnlySequence<byte> buffer, ref long byteIndex, ref int index, LongHorMetric[] data)
        {
            SequenceReader<byte> reader = new SequenceReader<byte>(buffer);
            reader.Advance(byteIndex);
            int length = data.Length;
            int size = Marshal.SizeOf<LongHorMetric>();
            while (reader.Remaining >= size && index < length)
            {
                reader.TryReadBigEndian(out short aw);
                reader.TryReadBigEndian(out short lsb);
                LongHorMetric local = new LongHorMetric
                {
                    AdvanceWidth = (ushort)aw,
                    LeftSideBearing = lsb
                };
                data[index++] = local;
                byteIndex += size;
            }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void ReadLsb(ref ReadOnlySequence<byte> buffer, ref long byteIndex, ref int index, short[] data)
        {
            SequenceReader<byte> reader = new SequenceReader<byte>(buffer);
            reader.Advance(byteIndex);
            int length = data.Length;
            while (reader.Remaining >= sizeof(short) && index < length)
            {
                reader.TryReadBigEndian(out short lsb);
                data[index++] = lsb;
                byteIndex += sizeof(short);
            }
        }
    }
}
